package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.CertificateDao;
import com.cci.kangdao.dao.TechnicianCertificateOperationHistoryDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.entity.FileEntity;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CertificateService;
import com.cci.kangdao.service.FileUploadService;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.StringToool;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("CertificateService")
public class CertificateServiceImpl implements CertificateService {
    private Logger log = Logger.getLogger(this.getClass().getName());
    @Autowired
    private CertificateDao dao;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private TechnicianCertificateOperationHistoryDao historyDao;

    //增加工作状态=空闲
    private static final String WORK_STATUS_FREE = "0";

    //增加工作状态=休假
    private static final String WORK_STATUS_TIME_OFF = "2";


    @Override
    public ModelAndView getTechnicianList(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        List<Map<String, Object>> technicianList = new ArrayList<>();
        if (0 < userT.getServiceStationID()) {
            technicianList = dao.getTechnicianList(userT.getServiceStationID());
        }
        ParameterTool.writeSuccessResponse(response, technicianList);
        return null;
    }

    @Override
    public ModelAndView getTechCertCourses(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");

        Long userId = MapUtils.getLongValue(map, "userId", 0);
        if (0 == userId) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }

        Map<String, Object> techCert = dao.getTechnicianCert(userId);

        Long certId = MapUtils.getLongValue(techCert, "certId", 0);
        if (0 != certId) {
            List<Map<String, Object>> certPics = dao.getTechnicianCertPics(certId);
            techCert.put("coursePics", certPics);
        }
        //判断当查询不到当前数据时默认不返回此字段
        if(!Objects.isNull(techCert)){
            techCert.put("serverTime",  LocalTimeUtil.getRealCurrentTime());
        }
        ParameterTool.writeSuccessResponse(response, techCert);
        return null;
    }

    @Override
    @Transactional
    public ModelAndView uploadTechCertCourses(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");

        UserT userT = UserThreadLocal.get();

        Long userId = MapUtils.getLongValue(map, "userId", 0);
        Long certId = MapUtils.getLongValue(map, "certId", 0);

        map.put("programId", MapUtils.getString(map, "programId", ""));

        if (userId == 0) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }


        if (certId == 0) {
            // 新建认证课程记录
            addCertificateRecord(map, userT, userId);
        } else {
            // 修改认证课程记录
            updateCertificateRecord(map, userT);
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }

    /**
     * 添加课程认证纪录
     *
     * @param map
     * @param userT
     * @param userId
     */
    private void addCertificateRecord(Map<String, Object> map, UserT userT, Long userId) {
        // 验证当前用户是否已经有了认证课程记录
        if (dao.getTechnicianCertCountByUserId(userId) > 0) {
            updateCertificateRecord(map, userT);
            return;
        }
        String key = "TechnicianCertificate" + userId;
        // 增加认证课程记录
        if (redisClientUtils.exists(key)) {
            return;
        } else {
            redisClientUtils.set(key, userId.toString(), 0);
        }
        // 添加认证课程记录
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        //判断工作状态是否为空或工作状态为休假状态时改为空闲状态
        map.put("creatorId", userT.getId());
        map.put("createTime", currentTime);
        //
        if (Objects.isNull(map.get("workStatus")) || WORK_STATUS_TIME_OFF.equals(map.get("workStatus"))) {
            map.put("workStatus", WORK_STATUS_FREE);
        }

        dao.addTechnicianCert(map);
        // 添加认证课程照片记录
        Long certId = MapUtils.getLongValue(map, "id", 0);
        if (certId == 0) {
            return;
        }
        uploadFiles(map, certId, userT.getId(), currentTime);
        redisClientUtils.delkey(key);
    }

    /**
     * 更新课程认证记录
     *
     * @param map
     * @param userT
     */
    private void updateCertificateRecord(Map<String, Object> map, UserT userT) {
        // 更新认证课程记录信息
        Long userId = MapUtils.getLongValue(map, "userId", 0);

        //保存历史记录
        Map<String, Object> oldHistory = dao.getTechnicianAllByUserId(userId);
        if (!Objects.isNull(oldHistory)){
            historyDao.insertByMap(oldHistory);
        }
        //保存历史记录完成
        String currentTime = LocalTimeUtil.getRealCurrentTime();

        Long certId = MapUtils.getLongValue(map, "certId", 0);
        String programId = MapUtils.getString(map, "programId", "");
        String workStatus = MapUtils.getString(map, "workStatus", WORK_STATUS_FREE);
        String startTimeOff = MapUtils.getString(map, "startTimeOff",null);
        String endTimeOff = MapUtils.getString(map, "endTimeOff",null);

        //增加判断工作状态是否存在
        if (Objects.isNull(map.get("workStatus")) || WORK_STATUS_TIME_OFF.equals(map.get("workStatus"))) {
            //如果工作状态为空，默认为空闲状态
            //0：空闲  1：忙碌  2：休假
            workStatus = MapUtils.getString(oldHistory,"workStatus",WORK_STATUS_FREE);
        }

        dao.updateTechnicianCert(certId, programId, userT.getId(), currentTime, workStatus, startTimeOff, endTimeOff);
        map.put("createTime", currentTime);
        // 处理认证课程照片记录
        uploadFiles(map, certId, userT.getId(), currentTime);

        String delPics = MapUtils.getString(map, "delPics", "");
        Pattern p = Pattern.compile("[,0-9]*");
        Matcher m = p.matcher(delPics);
        if (StringUtils.isNotBlank(delPics) && m.matches()) {
            List<String> stringList = StringToool.getStringList(delPics, ",");
            dao.updateTechnicianCertPics(stringList, userT.getId(), currentTime);
        }
    }

    /**
     * 上传照片
     *
     * @param map
     * @param certId
     * @param userId
     * @param currentTime
     */
    private void uploadFiles(Map<String, Object> map, Long certId, Long userId, String currentTime) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        List<FileEntity> fileList = fileUploadService.uploadFilesToAzure(request);
        if (CollectionUtils.isNotEmpty(fileList))
            dao.addTechnicianCertPics(certId, fileList, userId, currentTime);
    }

    @Override
    public ModelAndView uploadTechCertByUserId(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        Long userId = MapUtils.getLongValue(map, "userId", 0);
        Long certId = MapUtils.getLongValue(map, "certId", 0);
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        // 新建认证课程记录
        map.put("creatorId", UserThreadLocal.get().getId());
        map.put("createTime", currentTime);

        if (userId == 0) {
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }

        String key = "TechnicianCertificate" + userId;
        try{
            // 增加认证课程记录
            if (redisClientUtils.exists(key)) {
                ParameterTool.writeSuccessResponse(response);
                return null;
            } else {
                redisClientUtils.set(key, userId.toString(), 0);
            }
            log.error("uploadTechCertByUserId1----------certId="+certId);
            if (certId == 0) {
                //判断工作状态是否为空或工作状态为休假状态时改为空闲状态
                if (Objects.isNull(map.get("workStatus")) || WORK_STATUS_TIME_OFF.equals(map.get("workStatus"))) {
                    //如果工作状态为空，默认为空闲状态
                    //0：空闲  1：忙碌  2：休假
                    map.put("workStatus",WORK_STATUS_FREE);
                }
                dao.addTechnicianCert(map);
            } else {
                Map<String, Object> oldHistory = dao.getTechnicianAllByUserId(userId);

                //判断工作状态是否为空或工作状态为休假状态时改为空闲状态
                if (Objects.isNull(map.get("workStatus")) || WORK_STATUS_TIME_OFF.equals(map.get("workStatus"))) {
                    //如果工作状态为空，默认为空闲状态
                    //0：空闲  1：忙碌  2：休假
                    map.put("workStatus",MapUtils.getString(oldHistory,"workStatus",WORK_STATUS_FREE));
                }
                if (Objects.isNull(map.get("endTimeOff")) && Objects.isNull(map.get("startTimeOff"))) {
                    //如果工作状态为空，默认为空闲状态
                    //0：空闲  1：忙碌  2：休假
                    map.put("endTimeOff",null);
                    map.put("startTimeOff",null);
                }
                map.put("updator", UserThreadLocal.get().getId());
                map.put("updateTime", currentTime);

                dao.updateTechnicianCertById(map);
                if (!Objects.isNull(oldHistory)){
                    oldHistory.put("createTime",currentTime);
                    historyDao.insertByMap(oldHistory);
                }
            }
            ParameterTool.writeSuccessResponse(response);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }finally {
            redisClientUtils.delkey(key);
        }
        return null;
    }
}
